<template>
  <Form ref="formCom" class="xtx-form" :validation-schema="mySchema" v-slot="{errors}">
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field :class="{err:errors.account}" v-model="form.account" name='account' class="input" type="text" placeholder="请输入用户名" />
      </div>
      <div v-if="errors.account" class="error">{{errors.account}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err:errors.mobile}" v-model="form.mobile" name='mobile' class="input" type="text" placeholder="请输入手机号" />
      </div>
      <div v-if="errors.mobile" class="error">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" v-model="form.code" name='code' class="input" type="text" placeholder="请输入验证码" />
        <span @click="send" class="code">{{time ===0?'发送验证码':`${time}秒后发送`}}</span>
      </div>
     <div v-if="errors.code" class="error">{{errors.code}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{err:errors.password}" v-model="form.password" name='password' class="input" type="password" placeholder="请输入密码" />
      </div>
      <div v-if="errors.password" class="error">{{errors.password}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{err:errors.rePassword}" v-model="form.rePassword" name='rePassword' class="input" type="password" placeholder="请确认密码" />
      </div>
      <div v-if="errors.rePassword" class="error">{{errors.rePassword}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即提交</a>
  </Form>
</template>

<script>
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/core'
import schema from '@/utils/vee-validate-schema'
import { Form, Field } from 'vee-validate'
import { reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackPatch',
  components: {
    Form, Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // console.log(props.unionId)
    // 表单数据对象
    const form = reactive({
      account: null,
      mobile: null,
      code: null,
      password: null,
      rePassword: null
    })
    // 表单校验规则
    const mySchema = {
      account: schema.accountApi,
      mobile: schema.mobile,
      code: schema.code,
      password: schema.password,
      rePassword: schema.rePassword
    }
    // 验证码 定时器----------------------------------------
    const formCom = ref(null)
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })
    const send = async () => {
      // console.log(11111)
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        if (time.value !== 0) return
        try {
          await userQQPatchCode(form.mobile)
          time.value = 60
          resume()
          Message({ type: 'success', text: '发送成功' })
        } catch (error) {
          Message({ type: 'error', text: `${error.response.data.message}` } || '发送失败')
        }
      } else {
        // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
    }
    // 提交表单-----------------------------------
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      const valid = formCom.value.validate()
      if (valid) {
        try {
          const { result } = await userQQPatchLogin(form)
          console.log(result)
          store.commit('user/setUser', result)
          if (store.state.user.redirectUrl) {
            router.push(store.state.user.redirectUrl)
          } else {
            router.back()
          }
          Message({ type: 'success', text: 'QQ完善信息成功,即将跳转' })
          // 登录成功后合并购物车数据
          store.dispatch('cart/mergeLocalCart')
        } catch (error) {
          Message({ type: 'error', text: '完善信息失败' })
        }
      }
    }
    // 💥由于父组件获取 unionId 是异步的，可通过监听变化获取最新值
    watch(() => props.unionId, (unionId) => {
      form.unionId = unionId
    }, { immediate: true })
    return { mySchema, form, send, time, formCom, submit }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
